//
//  UIButton+convenience.swift
//  weiBo
//
//  Created by 胡卓 on 2017/4/2.
//  Copyright © 2017年 胡卓. All rights reserved.
//

import UIKit


extension UIButton {
    
    
    //至少有一个必须要传的，所有参数为默认值后，就以为着所有参数都可以不传，这样就会和默认的构造函数init（）方法冲突
    convenience init(title: String?,
                     titleColor: UIColor = UIColor.darkGray,
                     font: CGFloat = 14,
                     image: String? = nil,
                     bgImage: String? = nil,
                     target: AnyObject? = nil,
                     action: Selector? = nil,
                     events: UIControlEvents = .touchUpInside) {
        
        self.init()
        
        self.setTitle(title, for: .normal)
        self.setTitleColor(titleColor, for: .normal)
        self.titleLabel?.font = UIFont.systemFont(ofSize: font)
        
        //可选绑定(如果传了图片才设置)
        if let image = image {
            self.setImage(UIImage(named: image), for: .normal)
            self.setImage(UIImage(named: "\(image)_highlighted"), for: .highlighted)
        }
        
        //可选绑定(如果传了背景图片才设置)
        if let bgImage = bgImage {
            self.setBackgroundImage(UIImage(named: bgImage), for: .normal)
            self.setBackgroundImage(UIImage(named: "\(bgImage)_highlighted"), for: .highlighted)
        }
        
        //添加事件
        if let target = target, let action = action {
            
            self.addTarget(target, action: action, for: events)
        }
    }
}
